/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-11-28     RT-Thread    first version
 */

#include <rtthread.h>

#define THREAD_PRIORITY 9
#define THREAD_TIMESLICE 5

#define EVENT_FLAG3 (1<<3)
#define EVENT_FLAG5 (1<<5)


#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

static rt_uint8_t *ptr[50];
static rt_uint8_t mempool[4096];
static struct rt_mempool mp;

static char thread1_stack[1024];
static struct rt_thread thread1;
static char thread2_stack[1024];
static struct rt_thread thread2;


static void thread1_recv_event(void *param){
    int i;
    for(i=0;i<50;i++){
        if (ptr[i] == RT_NULL){
            ptr[i] = rt_mp_alloc(&mp, RT_WAITING_FOREVER);
            rt_kprintf("allocate No.%d\n",i);
        }else{
            rt_kprintf("allocate fail %d\n",i);
        }
    }
}

static void thread2_recv_event(void *param){
    int i;
    for(i=0;i<50;i++){
        if (ptr[i] != RT_NULL){
            rt_kprintf("free No.%d\n",i);
            rt_mp_free(ptr[i]);
            ptr[i] = RT_NULL;
        }
    }
}


int main(void)
{

    for(int i=0;i<50;i++){
        ptr[i] = RT_NULL;
    }
    rt_mp_init(&mp, "mp1", &mempool[0], sizeof(mempool), 80);

    rt_thread_init(&thread1,"thread1",thread1_recv_event,RT_NULL,&thread1_stack[0],sizeof(thread1_stack),THREAD_PRIORITY - 1,THREAD_TIMESLICE);
    rt_thread_startup(&thread1);
    rt_thread_init(&thread2,"thread2",thread2_recv_event,RT_NULL,&thread2_stack[0],sizeof(thread2_stack),THREAD_PRIORITY + 1,THREAD_TIMESLICE);
    rt_thread_startup(&thread2);

    return RT_EOK;
}
